package com.itheima.controller;

import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.service.MemberService;
import com.itheima.service.ReportService;
import com.itheima.service.SetMealService;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Program: health_parent
 * @Description: 报表相关操作
 * @Author: choulan
 * @Date:2020-11-17 11:48
 **/
@RestController
@RequestMapping("/report")
public class ReportController {
    @Reference
    private MemberService memberService;
    @Reference
    private SetMealService setMealService;
    @Reference
    private ReportService reportService;
    //获得会员数量统计信息
    @PreAuthorize("hasAuthority('REPORT_VIEW')")
    @RequestMapping("/getMemberReport")
    public Result getMemberReport(){
        try {
            //存储月份以及相应的数量
            Map<String,Object> map=new HashMap<>();
            //存储月份数据
            List<String> months=new ArrayList<>();
            //得到当前时间日历对象
            Calendar calendar=Calendar.getInstance();
            //往前推12个月的时间
            calendar.add(Calendar.MONTH,-12);
            for (int i = 0; i < 12; i++) {
                //往后推一个月
                calendar.add(Calendar.MONTH,1);
                Date date = calendar.getTime();
                months.add(new SimpleDateFormat("yyyy.MM").format(date));
            }
            map.put("months",months);
            //存储会员数量信息
            List<Integer> memberCount=memberService.findMemberCountByMonths( months);
            map.put("memberCount",memberCount);
            return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS,map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_MEMBER_NUMBER_REPORT_FAIL);
        }
    }


    //获得套餐预约占比统计数据
    @PreAuthorize("hasAuthority('REPORT_VIEW')")
    @RequestMapping("/getSetmealReport")
    public Result getSetmealReport(){
        try {
            Map<String,Object> data=new HashMap<>();
            //存储对应套餐数量
            List<Map<String,Object>> setmealCount=setMealService.findSetMealCount();
            data.put("setmealCount",setmealCount);
            //存储套餐名称信息
            List<String> setmealNames=new ArrayList<>();
            for (Map<String, Object> map : setmealCount) {
                String name = (String) map.get("name");
                setmealNames.add(name);
            }
            data.put("setmealNames",setmealNames);
            return new Result(true,MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS,data);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_SETMEAL_COUNT_REPORT_FAIL);
        }
    }

    //获得运营数据统计信息
    @PreAuthorize("hasAuthority('REPORT_VIEW')")
    @RequestMapping("/getBusinessReportData")
    public Result getBusinessReportData(){
        try {
            Map<String,Object> map=reportService.getBusinessReportData();
            return new Result(true,MessageConstant.GET_BUSINESS_REPORT_SUCCESS,map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }
    //导出excel表格信息
    @PreAuthorize("hasAuthority('REPORT_VIEW')")
    @RequestMapping("/exportBusinessReport")
    public Result exportBusinessReport(HttpServletRequest request, HttpServletResponse response){
        try {
            Map<String,Object> result=reportService.getBusinessReportData();
            //获得运营数据
            String reportDate = (String) result.get("reportDate");//今日日期
            Integer todayNewMember = (Integer) result.get("todayNewMember");//今日新增会员数
            Integer totalMember =(Integer) result.get("totalMember");//总会员数
            Integer thisWeekNewMember =(Integer) result.get("thisWeekNewMember");//本周新增会员数
            Integer thisMonthNewMember =(Integer) result.get("thisMonthNewMember");//本月新增会员数
            Integer todayOrderNumber =(Integer) result.get("todayOrderNumber");//今日预约数
            Integer todayVisitsNumber =(Integer) result.get("todayVisitsNumber");//今日到诊数
            Integer thisWeekOrderNumber =(Integer) result.get("thisWeekOrderNumber");//本周预约数
            Integer thisWeekVisitsNumber =(Integer) result.get("thisWeekVisitsNumber");//本周到诊数
            Integer thisMonthOrderNumber =(Integer) result.get("thisMonthOrderNumber");//本月预约数
            Integer thisMonthVisitsNumber =(Integer) result.get("thisMonthVisitsNumber");//本月到诊数
            //获得当前excel模板文件的路径
            String filePath = request.getSession().getServletContext().getRealPath("template") + File.separator + "report_template.xlsx";
            //获得excel模板文件
            XSSFWorkbook workbook=new XSSFWorkbook(new FileInputStream(new File(filePath)));
            //获得excel文件的第一个工作表
            XSSFSheet sheet = workbook.getSheetAt(0);
            //获得第3行第6列，并为其赋值
            XSSFRow row = sheet.getRow(2);
            XSSFCell cell = row.getCell(5);
            cell.setCellValue(reportDate);
            //获得第5行第6列，并为其赋值
            sheet.getRow(4).getCell(5).setCellValue(todayNewMember);
            //获得第5行第8列，并为其赋值
            sheet.getRow(4).getCell(7).setCellValue(totalMember);
            //获得第6行第6列，并为其赋值
            sheet.getRow(5).getCell(5).setCellValue(thisWeekNewMember);
            //获得第6行第8列，并为其赋值
            sheet.getRow(5).getCell(7).setCellValue(thisMonthNewMember);
            //获得第8行第6列，并为其赋值
            sheet.getRow(7).getCell(5).setCellValue(todayOrderNumber);
            //获得第8行第8列，并为其赋值
            sheet.getRow(7).getCell(7).setCellValue(todayVisitsNumber);
            //获得第9行第6列，并为其赋值
            sheet.getRow(8).getCell(5).setCellValue(thisWeekOrderNumber);
            //获得第9行第8列，并为其赋值
            sheet.getRow(8).getCell(7).setCellValue(thisWeekVisitsNumber);
            //获得第10行第6列，并为其赋值
            sheet.getRow(9).getCell(5).setCellValue(thisMonthOrderNumber);
            //获得第10行第8列，并为其赋值
            sheet.getRow(9).getCell(7).setCellValue(thisMonthVisitsNumber);
            //为13、14、15行赋值
            int rowNum=12;
            List<Map> hotSetmeal  = (List<Map>) result.get("hotSetmeal");
            for (Map map : hotSetmeal) {
                String name = (String) map.get("name");
                long setmeal_count = (long) map.get("setmeal_count");
                BigDecimal proportion = (BigDecimal) map.get("proportion");
                row=sheet.getRow(rowNum++);
                row.getCell(4).setCellValue(name);
                row.getCell(5).setCellValue(setmeal_count);
                row.getCell(6).setCellValue(proportion.doubleValue());
            }
            //使用输出流进行文件下载，基于浏览器客户端实现
            OutputStream os=response.getOutputStream();
            response.setContentType("application/vnd.ms-excel");//代表的是Excel文件类型
            response.setHeader("content-Disposition", "attachment;filename=report.xlsx");//指定以附件形式进行下载
            workbook.write(os);
            os.flush();
            os.close();
            workbook.close();
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }
    //导出PDF数据
    @PreAuthorize("hasAuthority('REPORT_VIEW')")
    @RequestMapping("/exportBusinessReport4PDF")
    public Result exportBusinessReport4PDF(HttpServletRequest request, HttpServletResponse response){
        try {
            Map<String,Object> result=reportService.getBusinessReportData();
            List<Map> hotSetmeal  = (List<Map>) result.get("hotSetmeal");
            //获得当前jasper模板文件的输入和输出路径
            String jrxmlPath = request.getSession().getServletContext().getRealPath("template") + File.separator + "health_business3.jrxml";
            String jasperPath = request.getSession().getServletContext().getRealPath("template") + File.separator + "health_business3.jasper";
            //编译模板
            JasperCompileManager.compileReportToFile(jrxmlPath,jasperPath);
            //填充数据，使用javaBean数据源填充
            JasperPrint jasperPrint= JasperFillManager.fillReport(jasperPath,result,new JRBeanCollectionDataSource(hotSetmeal));
            //使用输出流进行文件下载，基于浏览器客户端实现
            OutputStream os=response.getOutputStream();
            response.setContentType("application/pdf");//代表的是Excel文件类型
            response.setHeader("content-Disposition", "attachment;filename=report.pdf");//指定以附件形式进行下载
            //输出文件
            JasperExportManager.exportReportToPdfStream(jasperPrint,os);
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }
}
